const qiniu = require('qiniu');
const accessKey = 'XSD5WbJMtgf1ctD9FR2kbMfTxYDZWqPnB8sJ_b1h';
const secretKey = 'YLp_qCiaPZq4sYJVeT0-rBN1k2eBvj0HPGN54QmU';
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let options = {
  scope: 'tinyxu-wx',
  callbackBody:
    '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
  callbackBodyType: 'application/json',
};
var putPolicy = new qiniu.rs.PutPolicy(options);
var config = new qiniu.conf.Config();
// 空间对应的机房
config.zone = qiniu.zone.Zone_z2;
var formUploader = new qiniu.form_up.FormUploader(config);
var putExtra = new qiniu.form_up.PutExtra();

export const upload = (file: string, fileName: string) => {
  var uploadToken = putPolicy.uploadToken(mac);
  return new Promise((resolve, reject) => {
    formUploader.putFile(
      uploadToken,
      fileName,
      file,
      putExtra,
      function (respErr, respBody, respInfo) {
        if (respErr) {
          reject(respErr);
        }
        if (respInfo.statusCode == 200) {
          resolve(respBody);
        } else {
          console.log(`{ code:${respInfo.statusCode},mes:${respBody} }`);
        }
      },
    );
  });
};
